package com.hundsun.yr.universal.p2p.ui.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.adapter.HolderAdapter;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper.UpdateItem;
import com.hundsun.yr.universal.library.base.BaseAppManager;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.netstatus.NetUtils.NetType;
import com.hundsun.yr.universal.library.utils.MathUtils;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.view.hsdialog.ZDialog;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSLoadMoreListView;
import com.hundsun.yr.universal.p2p.bean.PrepayPlanBeen;
import com.hundsun.yr.universal.p2p.bean.RepayPlanBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.BaseListEntityPresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseActivity;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.utils.Logs;
import com.hundsun.yr.universal.p2p.view.base.BaseListView;
import com.hundsun.yr.universal.p2p.view.base.InitializeView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

/**
 * 还款计划
 */
public class RepayPlanActivity extends BaseActivity implements BaseListView, InitializeView, OnClickListener,
        UpdateItem<RepayPlanBeen>, HSDialog.HSDialogOnItemClickListener {

    private HSLoadMoreListView mListView;
    private HolderAdapter<RepayPlanBeen> mAdapter;
    private HSButton btn_revoke;

    /**
     * 数据集合
     **/
    ArrayList<RepayPlanBeen> data = new ArrayList<RepayPlanBeen>();

    /**
     * 商品ID
     **/
    private String goodsId;

    /**
     * 请求接口
     **/
    private RequestPresenter mPresenter = null;
    /**
     * 是否为已还借款列表进入
     **/
//	private boolean stateFlag = false;
    HashMap<String, String> map;
    /***/
    private HSButton btn_advance = null;
    private String zwgt_data;

    private String flag = "";
    private String repay = "REPAY";
    private String prepay = "PREPAY";
    /**
     * 还款dialog
     */
    private HSDialog dialog_repayment;

    /**
     * 提前还款dialog
     */
    private HSDialog dialog_prepayment;

    /**
     *  授权dialog
     */
    private HSDialog dialog_payFee;

    private ZDialog dialog_return;
    private int final2;
    private String prepayment_flag;
    private String prepayment_begin_date;
    private String prepayment_end_date;
    private String prepayPlanId;
    private String prepayment;
    private String prdprogress;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_revoke:
                //点击了提前还款，查询提前还款计划,将数据填写在dialog上，然后进行提前还款
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                Logs.e("productid:77777 " + goodsId);
                mPresenter.loadingData(TaskConstants.TASK_PREPAYPLAN, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.TASK_PREPAYPLAN +
                        "?productid=" + goodsId, Constants.EVENT_PROGRESS, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) +
                        TaskConstants.TASK_PREPAYPLAN + "?productid=" + goodsId, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
                break;
        }
    }

    private Drawable smallCircle;
    private Drawable smallCircleT;
    private int color_lineCircle;
    private int color_lineCircleT;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.act_repay_plan;
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void getBundleExtras(Bundle extras) {
        goodsId = extras.getString("goodsid");
        prepayment_flag = extras.getString("prepayment_flag");
        prepayment_begin_date = extras.getString("prepayment_begin_date");
        prepayment_end_date = extras.getString("prepayment_end_date");
        prepayment = extras.getString("repayment");
        prdprogress = extras.getString("prdprogress");
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void initViewsAndEvents() {
        findViews();
        setToolbarTitle(R.string.repay_plan);

        ViewCreatorHelper<RepayPlanBeen> creatorHelper = new ViewCreatorHelper<RepayPlanBeen>(R.layout.item_repay_plan, this);
        mAdapter = new HolderAdapter<RepayPlanBeen>(mContext, creatorHelper.viewCreator());
        mListView.setAdapter(mAdapter);

        smallCircle = getResources().getDrawable(R.drawable.drawable_repay_plan_smallcircle);
        smallCircleT = getResources().getDrawable(R.drawable.drawable_repay_plan_smallcircle_transparent);
        color_lineCircle = mContext.getResources().getColor(R.color.circle_item_repay_plan);
        color_lineCircleT = mContext.getResources().getColor(R.color.circle_item_repay_plan_transparent);
        mPresenter = new BaseListEntityPresenterImpl(mContext, this, "");
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        Logs.e("goodsid:77777 " + goodsId);
        mPresenter.loadingData(TaskConstants.TASK_REPAYPLAN, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.TASK_REPAYPLAN +
                "?goodsid=" + goodsId, Constants.EVENT_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) +
                TaskConstants.TASK_REPAYPLAN + "?goodsid=" + goodsId, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);

        // TODO: 2017/6/15 提前还款 根据prepayment_flag，prepayment_begin_data，prepament_end_date
        String prepaymentBeginTime = CommTool.date2time(prepayment_begin_date);
        String prepaymentEndTime = CommTool.date2time(prepayment_end_date);
        String currrentTime = System.currentTimeMillis() + "";

        //显示隐藏提前还款按钮
        if (TextUtils.equals(prepayment_flag, "1") && TextUtils.equals(prdprogress, "20") && TextUtils.equals(prepayment,"0")) {
            if (MathUtils.compare(currrentTime, prepaymentBeginTime) > 0 && MathUtils.compare(currrentTime, MathUtils.plus(prepaymentEndTime,"86400000")) < 0) {
                //处于这两个时间之间的是可以提前还款的产品将提前还款按钮显示出来
//                toolbar_menu.setText(R.string.repapayment);
                btn_revoke.setVisibility(View.VISIBLE);
                btn_revoke.setOnClickListener(this);
            }
        }
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        mImmersionBar.titleBar(R.id.common_toolbar).init();
    }

    /**
     * 获取UI
     */
    private void findViews() {
        mListView = findView(R.id.list_repay_plan);
        btn_revoke = findView(R.id.btn_revoke);
    }

    @Override
    protected boolean isApplyKitKatTranslucency() {
        return true;
    }

    @SuppressWarnings("rawtypes")
    @Override
    protected void onEveComming(EventCenter eventCenter) {

        switch (eventCenter.getEventCode()) {
            case Extras.FINISH:
                finish();
                break;

            default:
                break;
        }

    }

    @Override
    protected boolean isBindEventBusHere() {
        return true;
    }

    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        if (mListView == null) {
            mListView = findView(R.id.list_repay_plan);
        }
        return mListView;
    }

    @Override
    protected void onNetworkConnected(NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return true;
    }

    @Override
    protected boolean toggleOverridePendingTransition() {
        return false;
    }

    @Override
    protected TransitionMode getOverridePendingTransitionMode() {
        return null;
    }

    @Override
    public void refreshItem(View view, final int position, final RepayPlanBeen bean) {
        //第几期
        TextView tv_title = findView(view, R.id.repayplan_title);
        tv_title.setText(mContext.getString(R.string._term, position + 1));

        //还款日期
        TextView tv_repayplanDate = findView(view, R.id.repayplan_date);
        if (bean.actual_repay_time == null) {
            tv_repayplanDate.setText(mContext.getString(R.string.repay_time, bean.repay_date));
        } else {
            tv_repayplanDate.setText(mContext.getString(R.string.repay_time, bean.actual_repay_time));
        }

        //还款状态
        TextView tv_status = findView(view, R.id.status_repayplan);
        tv_status.setText(bean.getProgress(mContext));
        LinearLayout repayplan_btnlay = findView(view, R.id.repayplan_btnlay);

        //还款按钮
        HSButton btn_repay = findView(view, R.id.btn_repay);

        int i;
        for (i = 0; i < data.size(); i++) {
            if (TextUtils.equals(data.get(i).progress, "0")) {
                break;
            }
        }

        //根据不同的情况显示还款按钮|状态，根据不同的状态控制tv_status和btn_repay的显示和隐藏
        if (position == i) {
            if (TextUtils.equals(prepayment, "0")) {
                repayplan_btnlay.setVisibility(View.GONE);
                btn_repay.setVisibility(View.VISIBLE);
            } else {
                repayplan_btnlay.setVisibility(View.VISIBLE);
                btn_repay.setVisibility(View.GONE);
            }
        } else {
            repayplan_btnlay.setVisibility(View.VISIBLE);
            btn_repay.setVisibility(View.GONE);
        }


        //还款金额
        TextView tv_realrepay = findView(view, R.id.repayplan_realrepay);
        tv_realrepay.setText(bean.amount);

        if (bean.actual_repay_time != null && !bean.actual_repay_time.isEmpty()){
            //存在的时候显示actual_amount
            tv_realrepay.setText(bean.actual_amount);
        } else{
            tv_realrepay.setText(bean.amount);
        }

        final View line_below_1 = findView(view, R.id.line_below_1);
        final View line_below_2 = findView(view, R.id.line_below_2);
        final View line_below_3 = findView(view, R.id.line_below_3);
        final View line_above_2 = findView(view, R.id.line_above_2);
        //根据不同状态显示隐藏线线
        bean.dispalyStatus(line_below_1, line_below_2, line_below_3, line_above_2, data.get(0).id, data.get(data.size() - 1).id);

        /**
         * 还款按钮
         */
        final int final1 = i + 1;
        final2 = i;

        btn_repay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog_repayment = new HSDialog("当前还款:第" + final1 + "期", "还款金额" + data.get(final2).amount + "元",
                        getString(R.string.cancel), getString(R.string.sure), mContext,
                        RepayPlanActivity.this).setCancelable(false);//.setOnDismissListener(this);
                dialog_repayment.show();
                dialog_repayment.setOnItemClickListener(RepayPlanActivity.this);
            }
        });
    }

    @Override
    public <T> void refreshListData(List<T> data) {

    }

    @Override
    public <T> void addMoreListData(List<T> data) {

    }

    @Override
    public <T> void onFailure(String task_name) {

    }

    @Override
    public <T> void initializeViews(String task_name, T result) {
        if (result == null) return;
        switch (task_name) {
            case TaskConstants.TASK_REPAYPLAN://还款计划
                if (data.size() > 0) data.clear();
                if (result != null) {
                    data.addAll((Collection<? extends RepayPlanBeen>) result);
                }

                mAdapter.update(data);
                break;

            case TaskConstants.TASK_REPAY://还款
//                //成功了之后请求一次网络刷新页面
//                zwgt_data = BaseRequestTool2.getFormatedDateString();
//                mPresenter.loadingData(TaskConstants.TASK_REPAYPLAN, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.TASK_REPAYPLAN +
//                        "?goodsid=" + goodsId, Constants.EVENT_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) +
//                        TaskConstants.TASK_REPAYPLAN + "?goodsid=" + goodsId, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
                showToast(getString(R.string.mine_ready_success));
                finish();
                if (BaseAppManager.getInstance().getActivity(LoanDetailActivity.class) != null){
                    BaseAppManager.getInstance().getActivity(LoanDetailActivity.class).finish();
                }

                if (BaseAppManager.getInstance().getActivity(MineLoanActivity.class) != null){
                    BaseAppManager.getInstance().getActivity(MineLoanActivity.class).finish();
                }


                break;

            case TaskConstants.TASK_PREPAYPLAN://提前还款计划
                flag = prepay;
                if (result != null) {
                    PrepayPlanBeen prepayPlanBeen = (PrepayPlanBeen) result;
                    String actual_amount = prepayPlanBeen.actual_amount;
                    prepayPlanId = prepayPlanBeen.id;

                    dialog_prepayment = new HSDialog("确定提前还款", "提前还款总金额" + actual_amount + "元",
                            getString(R.string.cancel), getString(R.string.sure), mContext,
                            RepayPlanActivity.this).setCancelable(false);//.setOnDismissListener(this);
                    dialog_prepayment.show();
                    dialog_prepayment.setOnItemClickListener(RepayPlanActivity.this);
                }
                break;

            case TaskConstants.TASK_PREPAY://提前还款
                //提前还款成功
                //刷新一个借款页面
                finish();
                if (BaseAppManager.getInstance().getActivity(LoanDetailActivity.class) != null){
                    BaseAppManager.getInstance().getActivity(LoanDetailActivity.class).finish();
                }

                if (BaseAppManager.getInstance().getActivity(MineLoanActivity.class) != null){
                    BaseAppManager.getInstance().getActivity(MineLoanActivity.class).finish();
                }

                showToast(getString(R.string.mine_already_success));

//                zwgt_data = BaseRequestTool2.getFormatedDateString();
//                mPresenter.loadingData(TaskConstants.TASK_REPAYPLAN, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.TASK_REPAYPLAN +
//                        "?goodsid=" + goodsId, Constants.EVENT_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) +
//                        TaskConstants.TASK_REPAYPLAN + "?goodsid=" + goodsId, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);

                break;
            case TaskConstants.Task_FEE:
                dialog_payFee = new HSDialog("提示", result.toString(),
                        "暂不签约","确认签约", mContext,
                        RepayPlanActivity.this).setCancelable(false);//.setOnDismissListener(this);
                dialog_payFee.show();
                dialog_payFee.setOnItemClickListener(RepayPlanActivity.this);
                break;
            case TaskConstants.TASK_RETURN_MONEY:
                dialog_return=new  ZDialog(this, "暂不签约", result.toString(), "立即签约", R.style.MyDialog);
                dialog_return.show();
                dialog_return.setOnclickListener(new ZDialog.OnclickListener() {
                    @Override
                    public void OnClickListener() {
                        readyGo(ManagementActivity.class);
                    }
                });
                break;
        }
    }

    /**
     * 网络异常情况的套路
     *
     * @param task_name 任务名称
     * @param data
     * @param <T>
     */
    @Override
    public <T> void initializeError(String task_name, T data) {

    }

    @Override
    public void onItemClick(Object o, int position) {
        if ((HSDialog) o == dialog_repayment) {
            if (position != -1) {
                Logs.e("点确定还款" + ",final:" + final2 + ",data.size()" +data.size());
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                //还款
                JSONObject map = new JSONObject();
                try {
                    map.put("goodsid", goodsId);
                    // TODO: 2017/6/14 角标越界
                    //防止角标越界
                    if (final2 >= data.size()) {
                        return;
                    }

                    map.put("planid", data.get(final2).id);
                    Logs.e("planid: " , data.get(final2).id);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                JSONObject jsonParams = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
                mPresenter.loadingData(TaskConstants.TASK_REPAY, getString(R.string.root_url_test) + getString(R.string.api_trade_test) + TaskConstants.
                        TASK_REPAY, Constants.EVENT_PROGRESS, jsonParams, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, getString(R.string.api_trade_test) + TaskConstants
                        .TASK_REPAY, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
            }
        }else if ((HSDialog) o == dialog_prepayment) {
            if (position != -1) {
                Logs.e("确认提前还款");
                zwgt_data = BaseRequestTool2.getFormatedDateString();
                //还款
                JSONObject map = new JSONObject();
                try {
                    map.put("productid", goodsId);
                    map.put("planid", prepayPlanId);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                JSONObject jsonParams2 = CommTool.getJSONParams(map, sharedPreferences.getShareProf(UserInfo.TOKENID).substring(0, 24), zwgt_data);
                //提前还款
                mPresenter.loadingData(TaskConstants.TASK_PREPAY, getString(R.string.root_url_test) + getString(R.string.api_trade_test) + TaskConstants.
                        TASK_PREPAY, Constants.EVENT_PROGRESS, jsonParams2, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_POST, getString(R.string.api_trade_test) + TaskConstants
                        .TASK_PREPAY, sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
            }
        }else if(o==dialog_payFee){
            if(position!=-1){
                readyGo(ManagementActivity.class);
                finish();
            }
        }
    }
}
